/* 
 * Copyright (C) 2012 UTSChedule
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package utsc.apps.utschedule.ui.activities;

import java.util.ArrayList;

import utsc.apps.utschedule.R;
import utsc.apps.utschedule.UTSCheduleApp;
import utsc.apps.utschedule.UTSCheduleHomeActivity;
import utsc.apps.utschedule.classes.Exam;
import utsc.apps.utschedule.classes.Timetable;
import utsc.apps.utschedule.ui.ExamListFragment;
import utsc.apps.utschedule.ui.MessageDialogFragment;
import utsc.apps.utschedule.ui.activities.adapters.AssignmentListAdapter;
import utsc.apps.utschedule.ui.interfaces.OnSyncListener;
import utsc.apps.utschedule.util.database.DatabaseManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

/**
 * The main activity to host a view pager to show {@link utsc.apps.utschedule.ui.activities.AssignmentListFragment AssignmentListFragment} and {@link utsc.apps.utschedule.ui.ExamListFragment ExamListFragment} 
 * in a tabular manner. 
 *
 */
public class AssignmentExamMainActivity extends GenericFragmentActivity implements OnClickListener, OnSyncListener<Exam>{

	private boolean _updated=true;
	private ViewPager _pager;
	private AssignmentExamPagerAdapter _PagerAdapter;
	private ArrayList<Fragment> _fragments;
	public static final int TAG_ASSIGNMENT=1;
	public static final int TAG_EXAM=2;
	/**
	 * the empty layout for no active timetable set 
	 */
	private LinearLayout _emptyLayout;
	/**
	 * the activity class name that started this activity if set 
	 */
	private String _fromActivity;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Intent startIntent=getIntent();
		if (startIntent!=null) {
			//set the fromActivity string 
			_fromActivity=startIntent.getStringExtra("fromActivity");
		}
		
		setContentView(R.layout.activity_assign_exam);
		_emptyLayout=(LinearLayout) findViewById(R.id.empty_timetable_layout);
		setupAssignmentList();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if (!_updated) {
			_PagerAdapter.notifyDataSetChanged();
			_updated=true;
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch (item.getItemId()) {
		case android.R.id.home:
			if (_fromActivity==null) {
				navigateUp();
			}else {
				finish();
			}
			return true;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onBackPressed() {
		if (_fromActivity==null) {
			navigateUp();
		}
		else {
			super.onBackPressed();
		}
	}
	
	private void navigateUp() {
			Intent intent=new Intent(this,UTSCheduleHomeActivity.class);
			if (NavUtils.shouldUpRecreateTask(this, intent)) {
				NavUtils.navigateUpTo(this, intent);
			}else {
				NavUtils.navigateUpFromSameTask(this);
			}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return super.onCreateOptionsMenu(menu);
	}
	
	/**
	 * A general setup method to setup the view pager.
	 */
	public void setupAssignmentList() {
		UTSCheduleApp app=(UTSCheduleApp) getApplication();
		Timetable t=app.get_currentActiveTimetable();
		//we only setup the view pager if we have an active timetable
		if (t!=null) {
			//hide the empty view
			_emptyLayout.setVisibility(View.GONE);
			_fragments=new ArrayList<Fragment>();
			
			//setup the two fragments
			AssignmentListFragment fragment1=AssignmentListFragment.newInstance(t.get_timetableID());
			ExamListFragment fragment2=new ExamListFragment();
			
			_fragments.add(fragment1);
			_fragments.add(fragment2);
			_pager=(ViewPager)findViewById(R.id.pager);
			_PagerAdapter=new AssignmentExamPagerAdapter(getSupportFragmentManager(), _fragments, this);
			_pager.setAdapter(_PagerAdapter);
			_pager.setOffscreenPageLimit(2);
			_pager.setOnPageChangeListener(_PagerAdapter);
			
			//also setup the tabs for navigation
			final ActionBar actionBar=getSupportActionBar();
			actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
			actionBar.setDisplayHomeAsUpEnabled(true);
			Tab assignmentTab=actionBar.newTab().setText("Assignment").setTabListener(_PagerAdapter);
			Tab examTab=actionBar.newTab().setText("Exam").setTabListener(_PagerAdapter);
			actionBar.addTab(assignmentTab);
			actionBar.addTab(examTab);
			
		}else {
			_emptyLayout.setVisibility(View.VISIBLE);
		}
		
	}
	
	@Override
	public void onClick(View v) {
		
	}
	
	public void selectTab(int position){
		getSupportActionBar().setSelectedNavigationItem(position);
	}
	
	public void selectPage(int position){
		_pager.setCurrentItem(position);
	}
	
	/**
	 * The custom page adapter to hold the {@link AssignmentListFragment} and {@link ExamListFragment}. 
	 *
	 */
	public static class AssignmentExamPagerAdapter extends FragmentStatePagerAdapter implements OnPageChangeListener, TabListener{
		public static final int COUNT=2;
		private ArrayList<Fragment> _fragmentList;
		private Context _context;
				
		public AssignmentExamPagerAdapter(FragmentManager fm, ArrayList<Fragment> fragmentList,Context context) {
			super(fm);
			this._fragmentList=fragmentList;
			this._context=context;
		}
		@Override
		public Fragment getItem(int arg0) {
			return _fragmentList.get(arg0);
		}
		
		/**
		 * Notify the assignment list fragment has been changed by providing a course id.
		 * @param courseID
		 */
		public void notifyDataSetChanged(int courseID) {
			super.notifyDataSetChanged();
			if (_fragmentList!=null) {
				((AssignmentListAdapter)((AssignmentListFragment)_fragmentList.get(0)).getExpandableListAdapter()).notifyDataSetChanged(courseID);
			}
		}
		
		@Override
		public int getCount() {
			return COUNT;
		}
		
		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}
		
		@Override
		public void onTabSelected(Tab tab, FragmentTransaction ft) {
			((AssignmentExamMainActivity)_context).selectPage(tab.getPosition());
		}
		@Override
		public void onTabUnselected(Tab tab, FragmentTransaction ft) {
			
		}
		@Override
		public void onTabReselected(Tab tab, FragmentTransaction ft) {
			
		}
		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}
		@Override
		public void onPageSelected(int arg0) {
			((AssignmentExamMainActivity)_context).selectTab(arg0);
		}
	}

	@Override
	public void onSyncCompleted(ArrayList<Exam> result) {
		if (result!=null&&!result.isEmpty()) {
			DatabaseManager.getInstance(this).saveSyncExam(result);
			((ExamListFragment)_fragments.get(1)).refreshExams();
			showDialogFragment(MessageDialogFragment.newInstance("Sync Completed", "-Your exams are synced successfully!\n-Please note that you need to update the weights independantly."), MessageDialogFragment.TAG);
		}else {
			showDialogFragment(MessageDialogFragment.newInstance("No Exam schedule found", "We are unable to find your exam schedule at the moment, please try again later."), MessageDialogFragment.TAG);
		}
	}

}
